package com.xgkj.diyiketang.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.umeng.analytics.MobclickAgent;
import com.xgkj.diyiketang.EatShowApp;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.LoginActivity;
import com.xgkj.diyiketang.activity.MainActivity;
import com.xgkj.diyiketang.activity.MyMessageActivity;
import com.xgkj.diyiketang.activity.SearchActivity;
import com.xgkj.diyiketang.data.CityInfo;
import com.xgkj.diyiketang.data.CountryInfo;
import com.xgkj.diyiketang.data.SchoolInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.task.AreaCitySchoolTask;
import com.xgkj.diyiketang.task.IsHaveJLPTask;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.weidget.kankan.OnWheelChangedListener;
import com.xgkj.diyiketang.weidget.kankan.OnWheelClickedListener;
import com.xgkj.diyiketang.weidget.kankan.WheelView;
import com.xgkj.diyiketang.weidget.kankan.adapters.ArrayWheelAdapter;
import com.xgkj.diyiketang.yizhibo.Constants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by XCKJ_Paladowow on 2016/5/23.
 */
public class ShouYeFragment extends BaseFragment implements RadioGroup.OnCheckedChangeListener, View.OnClickListener, OnWheelChangedListener, OnWheelClickedListener {
    private Context mContext;
    //private ViewPager viewPager;
    private RadioGroup rgChannel = null;
    private HorizontalScrollView hvChannel;
    // private PageFragmentAdapter adapter=null;
    private List<Fragment> fragmentList = new ArrayList<Fragment>();
    private int screenWidth;

    private int mCheckId;
    private int beforeCheckId;
    private int last_index = 0;
    private Fragment tuijianFragment;
    private Fragment mishiFragment;
    private Fragment yuefanFragment;
    //    private Fragment yuefanSJFragment;
//    private Fragment jilupianFragment;
    private Fragment saishiFragment;

    private Fragment yuanwangFragment;

    private RadioButton tuijianBtn;
    private RadioButton mishiBtn;
    private RadioButton yuefanBtn;
    private RadioButton jilupianBtn;
    private RadioButton saishiBtn;

    private static final String FRAGMENT_KEY_TUIJIAN = "shouye_tuijian";
    private static final String FRAGMENT_KEY_MISHI = "shouye_mishi";
    private static final String FRAGMENT_KEY_YUEFAN = "shouye_yuefan";
    private static final String FRAGMENT_KEY_YUEFAN_SJ = "shouye_yuefan_sj";
    private static final String FRAGMENT_KEY_JILUPIAN = "shouye_jilupian";
    private static final String FRAGMENT_KEY_SAISHI = "shouye_saishi";
    private static final String CURRENT_INDEX = "shouye_current_index";
    private static final String FRAGMENT_KEY_YUANWANG = "shouye_yuanwang";


    private ImageView searchText;
    public LocationClient mLocationClient;
    public MyLocationListener mMyLocationListener;
    // private LocationClientOption.LocationMode tempMode = LocationClientOption.LocationMode.Hight_Accuracy;
    private String tempcoor = "gcj02";
    private TextView local_video;
    private String localstring = "中国";
    private ImageView myMgsView;
    private WeiduReceive weiduReceiver = null;
    private String mLocalFrist;
    private RelativeLayout mTopLayout;
    private AlphaAnimation mAlphaAnimation;
    private TranslateAnimation mTranslateAnimation;
    private RelativeLayout mainLayout;
    float desity;
    private int ishaveJLPTaskId = -1;
    private View rootView;
    private boolean isbusiness;
    private int getSchoolTaskId = -1;
    private String[] allCounties;
    private boolean isVisiable = false;
    /**
     * key - 国家 value - 市
     */
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    /**
     * key - 市 values - 学校
     */
    protected Map<String, String[]> mSchoolDatasMap = new HashMap<String, String[]>();
    /**
     * 当前省的名称
     */
    protected String mCurrentProviceName;
    /**
     * 当前市的名称
     */
    protected String mCurrentCityName;

    /**
     * 当前学校的名称
     */
    protected String mCurrentDistrictName = "";

    private InputMethodManager im;
    private LinearLayout address_pop;
    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;
    private Button mBtnConfirm;
    private Button mBtnCancel;

    @Override
    protected int getContentViewId() {
        return 0;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.shouye, null);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        mContext = getActivity();
        screenWidth = ViewUtil.getScreenWidth(mContext);

        mLocationClient = new LocationClient(mContext);
        mMyLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mMyLocationListener);

        if (weiduReceiver == null) {
            weiduReceiver = new WeiduReceive();
            IntentFilter messageFilter = new IntentFilter(VideoFragment.WEIDUMESSAGE_ACTION);
            mContext.registerReceiver(weiduReceiver, messageFilter);
        }
        im = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        initView(rootView);
        restoreFragment(savedInstanceState);
        initFragment();
        rgChannel.setOnCheckedChangeListener(this);
        if (last_index != 0) {
            rgChannel.check(last_index);
        } else {
            tuijianBtn.setChecked(true);
        }
        return rootView;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    private void initView(View view) {
        desity = ViewUtil.getScreenDesity(mContext);

        mainLayout = (RelativeLayout) view.findViewById(R.id.main_layout);
        mTopLayout = (RelativeLayout) view.findViewById(R.id.top);
        mAlphaAnimation = new AlphaAnimation(1.0f, 0.0f);
        mAlphaAnimation.setDuration(500);
        mTranslateAnimation = new TranslateAnimation(0, 0, 0, -44 * desity);
        mTranslateAnimation.setDuration(500);
        mTranslateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mTopLayout.clearAnimation();
                mainLayout.clearAnimation();
                mTopLayout.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        myMgsView = (ImageView) view.findViewById(R.id.mymessage);
        myMgsView.setOnClickListener(this);
        local_video = (TextView) view.findViewById(R.id.local_video);
        local_video.setOnClickListener(this);
        searchText = (ImageView) view.findViewById(R.id.search);
        searchText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext, SearchActivity.class));
            }
        });

        getLocation();
        rgChannel = (RadioGroup) view.findViewById(R.id.rgChannel);
        hvChannel = (HorizontalScrollView) view.findViewById(R.id.hvChannel);
        tuijianBtn = (RadioButton) view.findViewById(R.id.tab_tuijian);
        mishiBtn = (RadioButton) view.findViewById(R.id.tab_mishi);
        yuefanBtn = (RadioButton) view.findViewById(R.id.tab_yuefan);
        jilupianBtn = (RadioButton) view.findViewById(R.id.tab_jilupian);
        saishiBtn = (RadioButton) view.findViewById(R.id.tab_saishibang);

//        doIsHaveJLP();
        RadioGroup.LayoutParams params = new
                RadioGroup.LayoutParams(screenWidth / 4,
                RadioGroup.LayoutParams.WRAP_CONTENT);
        rgChannel.removeAllViews();
        rgChannel.addView(tuijianBtn, params);
        rgChannel.addView(mishiBtn, params);
        rgChannel.addView(saishiBtn, params);
        rgChannel.addView(jilupianBtn, params);
        rgChannel.addView(yuefanBtn, params);

        rgChannel.check(0);

        address_pop = (LinearLayout) view.findViewById(R.id.address_pop);
        address_pop.setVisibility(View.GONE);

        setUpViews(view);
        setUpListener();
        doGetAreaSchool();
    }

    private void setUpViews(View v) {
        mViewProvince = (WheelView) v.findViewById(R.id.id_province);
        mViewCity = (WheelView) v.findViewById(R.id.id_city);
        mViewDistrict = (WheelView) v.findViewById(R.id.id_district);
        mBtnConfirm = (Button) v.findViewById(R.id.btn_confirm);
        mBtnCancel = (Button) v.findViewById(R.id.btn_cancel);
    }

    private void setUpListener() {
        // 添加change事件
        mViewProvince.addChangingListener(this);
        // 添加change事件
        mViewCity.addChangingListener(this);
        // 添加change事件
        mViewDistrict.addChangingListener(this);
//        mViewDistrict.addClickingListener(this);
        // 添加onclick事件
        mBtnConfirm.setOnClickListener(this);
        mBtnCancel.setOnClickListener(this);
    }

    private void setUpData() {
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(mContext, allCounties));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        mViewDistrict.setVisibleItems(7);
        updateCities();
        updateAreas();
    }

    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        String[] citys = mCitisDatasMap.get(mCurrentProviceName);
        String[] areas = null;
        if (citys == null || citys.length == 0) {
            mCurrentCityName = "";
        } else {
            mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
            areas = mSchoolDatasMap.get(mCurrentCityName);
        }

        if (areas == null || areas.length == 0) {
            areas = new String[]{""};
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(mContext, areas));
        mViewDistrict.setCurrentItem(0);
        if (areas != null && areas.length > 0) {
            mCurrentDistrictName = areas[0];
        } else {
            mCurrentDistrictName = "";
        }
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = allCounties[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null || cities.length == 0) {
            cities = new String[]{""};
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(mContext, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }

    private void doIsHaveJLP() {
        IsHaveJLPTask task = new IsHaveJLPTask();
        task.addListener(new IsHaveListener(mContext));
        ishaveJLPTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void doGetAreaSchool() {
        AreaCitySchoolTask acsTask = new AreaCitySchoolTask();
        acsTask.addListener(new IsHaveListener(mContext));
        getSchoolTaskId = getEatShowApp().getTaskManager().addTask(acsTask);
    }

    //    private void doGetAreaSchool() {
//        UpdateNickOrSignTask updateArea = new UpdateNickOrSignTask();
//        acsTask.addListener(new IsHaveListener(mContext));
//        getSchoolTaskId = getEatShowApp().getTaskManager().addTask(acsTask);
//    }
//
    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
// TODO Auto-generated method stub
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict) {
            if (mSchoolDatasMap.get(mCurrentCityName) != null && mSchoolDatasMap.get(mCurrentCityName).length > 0) {
                mCurrentDistrictName = mSchoolDatasMap.get(mCurrentCityName)[newValue];
            } else {
                mCurrentDistrictName = "";
            }


//            new Handler().postDelayed(new Runnable(){
//                public void run() {
//                    address_pop.setVisibility(View.GONE);
//                    ToastUtil.showMessage(mContext, mCurrentDistrictName);
//                    local_video.setText(mCurrentDistrictName);
//                }
//            }, 1000);
        }
    }

    @Override
    public void onItemClicked(WheelView wheel, int itemIndex) {
        if (wheel == mViewDistrict) {
//            address_pop.setVisibility(View.GONE);
            mViewDistrict.setCurrentItem(itemIndex, true);
            mCurrentDistrictName = mSchoolDatasMap.get(mCurrentCityName)[itemIndex];
            address_pop.setVisibility(View.GONE);
            local_video.setText(mCurrentDistrictName);
            ToastUtil.showMessage(mContext, mCurrentDistrictName);
        }
    }

    class IsHaveListener extends ShowToastTaskEventListener {

        public IsHaveListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == ishaveJLPTaskId) {
                ishaveJLPTaskId = -1;

                if (data != null) {

                    JSONObject json = (JSONObject) data;
                    String isHave = json.getString("typeId");
                    PalLog.e("是否返回纪录片", isHave);
                    if (isHave != null) {
                        RadioGroup.LayoutParams params = new
                                RadioGroup.LayoutParams(screenWidth / 3,
                                RadioGroup.LayoutParams.WRAP_CONTENT);
                        rgChannel.addView(jilupianBtn, params);

                    }

                }
            } else if (taskId == getSchoolTaskId) {
                List<CountryInfo> countryList = new ArrayList<CountryInfo>();
                if (data != null) {

                    countryList = (List<CountryInfo>) data;
                    allCounties = new String[countryList.size()];
                    if (countryList != null && countryList.size() > 0) {

                        for (int i = 0; i < countryList.size(); i++) {
                            allCounties[i] = countryList.get(i).getCountryName();
                            List<CityInfo> cityList = countryList.get(i).getList();
                            String[] allCities = new String[cityList.size()];
                            if (cityList != null && cityList.size() > 0) {
                                for (int j = 0; j < cityList.size(); j++) {
                                    allCities[j] = cityList.get(j).getCityName();
                                    List<SchoolInfo> schoolList = cityList.get(j).getSchoolList();
                                    String[] allSchool = new String[schoolList.size()];
                                    if (schoolList != null && schoolList.size() > 0) {
                                        for (int k = 0; k < schoolList.size(); k++) {
                                            allSchool[k] = schoolList.get(k).getSchoolName();
                                        }
                                        mSchoolDatasMap.put(allCities[j], allSchool);
                                    }

                                }
                            }

                            mCitisDatasMap.put(countryList.get(i).getCountryName(), allCities);

                        }
                    }


                    if (countryList != null && !countryList.isEmpty()) {
                        mCurrentProviceName = countryList.get(0).getCountryName();
                        List<CityInfo> cityList = countryList.get(0).getList();
                        if (cityList != null && !cityList.isEmpty()) {
                            mCurrentCityName = cityList.get(0).getCityName();
                            List<SchoolInfo> districtList = cityList.get(0).getSchoolList();
                            if (districtList != null && !districtList.isEmpty()) {
                                mCurrentDistrictName = districtList.get(0).getSchoolName();
                            }

                        }
                    }
                    setUpData();
                }


            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    }

    private void getLocation() {
        PalLog.e("TAG", "定位中");
        initBaiduLocation();
        mLocationClient.start();
    }


    private void initBaiduLocation() {
        LocationClientOption option = new LocationClientOption();
        //option.setLocationMode(tempMode);//设置定位模式
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType(tempcoor);//返回的定位结果是百度经纬度，默认值gcj02
        //option.setScanSpan(10000);//设置发起定位请求的间隔时间为5000ms
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
    }

    /**
     * 滑动ViewPager时调整ScroollView的位置以便显示按钮
     *
     * @param idx
     */
    private void setTab(int idx) {
        RadioButton rb = (RadioButton) rgChannel.getChildAt(idx);
        rb.setChecked(true);
        int left = rb.getLeft();
        int width = rb.getMeasuredWidth();
        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int screenWidth = metrics.widthPixels;
        int len = left + width / 2 - screenWidth / 2;
        hvChannel.smoothScrollTo(len, 0);//滑动ScroollView

    }


    private void restoreFragment(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            FragmentManager fm = getActivity().getSupportFragmentManager();
            tuijianFragment = fm.findFragmentByTag(FRAGMENT_KEY_TUIJIAN);//fm.getFragment(savedInstanceState, FRAGMENT_KEY_TUIJIAN);
            mishiFragment = fm.findFragmentByTag(FRAGMENT_KEY_MISHI);//fm.getFragment(savedInstanceState, FRAGMENT_KEY_MISHI);
            saishiFragment = fm.findFragmentByTag(FRAGMENT_KEY_SAISHI);//fm.getFragment(savedInstanceState, FRAGMENT_KEY_SAISHI);
            yuefanFragment = fm.findFragmentByTag(FRAGMENT_KEY_YUEFAN);//fm.getFragment(savedInstanceState, FRAGMENT_KEY_YUEFAN);
//            yuefanSJFragment = fm.findFragmentByTag(FRAGMENT_KEY_YUEFAN_SJ);
//            jilupianFragment = fm.findFragmentByTag(FRAGMENT_KEY_JILUPIAN);//fm.getFragment(savedInstanceState, FRAGMENT_KEY_JILUPIAN);

            yuanwangFragment = fm.findFragmentByTag(FRAGMENT_KEY_YUANWANG);

            last_index = savedInstanceState.getInt(CURRENT_INDEX);
        }
    }


    private void initFragment() {
        if (tuijianFragment == null) {
            tuijianFragment = new Fragment_TuiJian();
        }

        if (mishiFragment == null) {
            mishiFragment = new Fragment_DaTi();
        }

        if (saishiFragment == null) {
            saishiFragment = new SchoolReportFragment();
        }


        if (yuefanFragment == null) {
            yuefanFragment = new Fragment_NaXin();
        }

        if (yuanwangFragment == null) {
            yuanwangFragment = new MallFragment();
        }

//        if(yuefanSJFragment == null){
//            yuefanSJFragment = new Fragment_NaXin();
//        }
//
//        if (jilupianFragment == null) {
//            jilupianFragment = new Fragment_NaXin();
//        }


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (weiduReceiver != null) {
            mContext.unregisterReceiver(weiduReceiver);
            weiduReceiver = null;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("VideoFragment");
        updateUnreadAddressLable();
        int type = ((MainActivity) getActivity()).getGoXyb();
        if (type == 1) {
            tuijianBtn.setChecked(true);
        } else if (type == 2) {
            yuefanBtn.setChecked(true);
        }
        ((MainActivity) getActivity()).setGoXyb(3);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("VideoFragment");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // String
        if (data != null) {


            localstring = data.getExtras().getString("areaName");

            // mListViewAdapter.setAreaName(localstring);
            local_video.setText(localstring);
            Fragment_TuiJian ft = (Fragment_TuiJian) getFragmentManager().findFragmentByTag(FRAGMENT_KEY_TUIJIAN);
            EatShowSetting.getInstance(mContext).setLocal(localstring);
            ft.getfoodList();


            EatShowApp.getACache().put(Constants.USER_LOCATION, localstring);
            //mListViewAdapter.clearData();
            //getfoodList();
        }


    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (mCheckId == checkedId) {
            return;
        }
        beforeCheckId = mCheckId;
        mCheckId = checkedId;
        switch (checkedId) {
            case R.id.tab_tuijian:
                setTab(0);
                stopMyAnimation();
                replaceFragment(FRAGMENT_KEY_TUIJIAN, tuijianFragment);
                break;
            case R.id.tab_mishi:
                if (getEatShowApp().getmUserInfo() != null) {
                    setTab(1);
                    startMyAnimation();
                    replaceFragment(FRAGMENT_KEY_MISHI, mishiFragment);
                } else {
                    startActivity(new Intent(mContext, LoginActivity.class));
                }

                break;
            case R.id.tab_saishibang:
                if (getEatShowApp().getmUserInfo() != null) {
                    setTab(2);
                    startMyAnimation();
                    replaceFragment(FRAGMENT_KEY_JILUPIAN, saishiFragment);
                } else {
                    startActivity(new Intent(mContext, LoginActivity.class));
                }
                break;
            case R.id.tab_jilupian:
                if (getEatShowApp().getmUserInfo() != null) {
                    setTab(3);
                    startMyAnimation();
                    replaceFragment(FRAGMENT_KEY_YUANWANG, yuanwangFragment);
                } else {
                    startActivity(new Intent(mContext, LoginActivity.class));
                }

                break;
            case R.id.tab_yuefan:
                if (getEatShowApp().getmUserInfo() != null) {
                    setTab(4);
                    startMyAnimation();
                    replaceFragment(FRAGMENT_KEY_YUEFAN, yuefanFragment);
                } else {
                    startActivity(new Intent(mContext, LoginActivity.class));
                }

                break;


            default:
                break;
        }
    }

    private void replaceFragment(String tag, Fragment mFragment) {
        FragmentManager fm = getActivity().getSupportFragmentManager();
        FragmentTransaction fts = fm.beginTransaction();
        if (tuijianFragment.isAdded()) {
            fts.hide(tuijianFragment);
        }

        if (mishiFragment.isAdded()) {
            fts.hide(mishiFragment);
        }

        if (saishiFragment.isAdded()) {
            fts.hide(saishiFragment);
        }


        if (yuefanFragment.isAdded()) {
            fts.hide(yuefanFragment);
        }

        if (yuanwangFragment.isAdded()) {
            fts.hide(yuanwangFragment);
        }

//        if(yuefanSJFragment.isAdded()){
//            fts.hide(yuefanSJFragment);
//        }

//        if (jilupianFragment.isAdded()) {
//            fts.hide(jilupianFragment);
//        }


        if (mFragment.isAdded()) {
            fts.show(mFragment);
        } else {
            fts.add(R.id.fragment_content, mFragment, tag);
        }

        fts.commitAllowingStateLoss();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mymessage:
                //getFragmentManager().beginTransaction().replace(R.id.content, new MessageFragment()).commit();
//                Intent intent = new Intent(mContext, MyMessageActivity.class);
//                startActivity(intent);
                if (getEatShowApp().getmUserInfo() != null) {
                    Intent intent = new Intent(mContext, MyMessageActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.local_video:
//                Intent cintent = new Intent(mContext, CityListActivity.class);
//                startActivityForResult(cintent, 1);
//                doGetAreaSchool();
                if (isVisiable == false) {
                    isVisiable = true;
                    address_pop.setVisibility(View.VISIBLE);
                } else {
                    isVisiable = false;
                    address_pop.setVisibility(View.GONE);
                }
                im.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
                break;

            case R.id.btn_confirm:
                address_pop.setVisibility(View.GONE);
                local_video.setText(mCurrentDistrictName);
                EatShowApp.getACache().put(Constants.USER_LOCATION, mCurrentDistrictName);

//                FragmentManager fm = getActivity().getSupportFragmentManager();
//                xxxFragment = (xxxFragment)fm.findFragmentByTag("xxx")
                Fragment_TuiJian ft = (Fragment_TuiJian) getFragmentManager().findFragmentByTag(FRAGMENT_KEY_TUIJIAN);
                ft.setSchoolName(mCurrentDistrictName);
                ft.getViewList();
                break;
            case R.id.btn_cancel:
                address_pop.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }


    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            //Receive Location
            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            sb.append("\ncity : ");
            sb.append(location.getCity());

            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 单位：公里每小时
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 单位：米
                sb.append("\ndirection : ");
                sb.append(location.getDirection());// 单位度
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");
//                localstring = location.getCity();
//                mListViewAdapter.setAreaName(localstring);
//                EatShowSetting.getInstance(mContext).setLocal(localstring);
                localstring = location.getCity();
                mLocalFrist = location.getCity();
                //  mListViewAdapter.setAreaName(localstring);
                EatShowSetting.getInstance(mContext).setLocal(localstring);
                EatShowSetting.getInstance(mContext).setFirstLocal(mLocalFrist);


            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\nprovice : ");
                sb.append(location.getProvince());
                sb.append("\ncity : ");
                local_video.setText(location.getCity());
                EatShowApp.getACache().put(Constants.USER_LOCATION, location.getCity());

//                localstring = location.getCity();
//                EatShowSetting.getInstance(mContext).setLocal(localstring);
//                mListViewAdapter.setAreaName(localstring);
                localstring = location.getCity();
                mLocalFrist = location.getCity();
                //mListViewAdapter.setAreaName(localstring);
                EatShowSetting.getInstance(mContext).setLocal(localstring);
                EatShowSetting.getInstance(mContext).setFirstLocal(mLocalFrist);

                //运营商信息
                sb.append("\noperationers : ");
                sb.append(location.getOperators());
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());// 位置语义化信息
            List<Poi> list = location.getPoiList();// POI数据
            if (list != null) {

                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }
            PalLog.e("BaiduLocationApiDem", sb.toString());
            if (location != null) {
                mLocationClient.stop();
                PalLog.e("定位完成", "百度定位完成");

            }
        }
    }

    public class WeiduReceive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            refresh();
        }
    }

    public void refresh() {
        updateUnreadAddressLable();
    }

    private int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
        unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
        for (EMConversation conversation : EMChatManager.getInstance().getAllConversations().values()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }

    /**
     * 刷新申请与通知消息数
     */
    private void updateUnreadAddressLable() {
//        int count = getUnreadMsgCountTotal();
//        PalLog.e("@@@@@@@@@@@消息未读数:", count + "");
//                if (count > 0) {
//
//                    unreadAddressLable.setVisibility(View.VISIBLE);
//                } else {
//                    unreadAddressLable.setVisibility(View.INVISIBLE);
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                int count = getUnreadMsgCountTotal();
                if (count > 0) {
//					unreadAddressLable.setText(String.valueOf(count));
                    // unreadAddressLable.setVisibility(View.VISIBLE);
                    myMgsView.setBackgroundResource(R.drawable.youxiaoxi);

                } else {
                    // unreadAddressLable.setVisibility(View.INVISIBLE);
                    myMgsView.setBackgroundResource(R.drawable.message_logo);
                }

            }
        });
//                }
    }

    private void startMyAnimation() {
        if (mTopLayout.getVisibility() == View.VISIBLE) {
            mTopLayout.startAnimation(mAlphaAnimation);
            mainLayout.startAnimation(mTranslateAnimation);
        }
    }

    private void stopMyAnimation() {
        if (mTopLayout.getVisibility() == View.GONE) {
            mTopLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            int type = ((MainActivity) getActivity()).getGoXyb();
            if (type == 1) {
                tuijianBtn.setChecked(true);
            } else if (type == 2) {
                yuefanBtn.setChecked(true);
            }
            ((MainActivity) getActivity()).setGoXyb(3);
        }
    }

    public void hidePopSchool() {
        address_pop.setVisibility(View.GONE);
    }

    public boolean isShow() {
        return address_pop.getVisibility() == View.VISIBLE;
    }

}
